package com.ruoyi.ruoyiqywechat.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.utils.ExtreUtls;
import com.ruoyi.common.qy.utils.SnowflakeUtils;
import com.ruoyi.common.qy.vo.DouYinVideoVo;
import com.ruoyi.common.qy.vo.XiaoHongShuVideoVo;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.service.XiaoHongShuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 小红书
 */
@RestController
@RequestMapping("/xhs/api")
public class XiaoHongShuController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private XiaoHongShuService xiaoHongShuService;
    /**
     * （小红书）根据小红书分享链接提取视频链接url
     * @param map
     * @return
     */
    @PostMapping("getXiaoHongShuVideo")
    public R<HashMap<String, String>> getXiaoHongShuVideo(HttpServletRequest request, @RequestBody HashMap<String,String> map){
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CrmebException("请先登录!");
        }
        String userId = JwtUtils.getUserId(token);
        String text = map.get("text");
        System.out.println("getXiaoHongShuVideo小红书分享链接["+text+"]");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("videoId",null);
        stringStringHashMap.put("url",null);
        // 提取单个链接
        Optional<String> link = ExtreUtls.extractLinkXiaoHongShu(text);
        if (link.isPresent()) {
            System.out.println("✅ 提取到链接: " + link.get());
            String videoId = SnowflakeUtils.nextIdString();
            XiaoHongShuVideoVo xiaoHongShuVideoVo = XiaoHongShuVideoVo.getInstance();
            xiaoHongShuVideoVo.setVideoId(videoId);
            xiaoHongShuVideoVo.setOldUrl(link.get());
            xiaoHongShuVideoVo.setUrl("");
            xiaoHongShuVideoVo.setExtracting(true);
            xiaoHongShuVideoVo.setExtractProgress(10);
            xiaoHongShuVideoVo.setExtractStep(0);
            redisUtil.lSet(CacheConstants.XIAOHONGSHU_CREATE +userId, videoId,System.currentTimeMillis());//存顺序有序
            redisUtil.hset(CacheConstants.XIAOHONGSHU_CREATE_HASH +userId,videoId, JSONObject.toJSONString(xiaoHongShuVideoVo));//hash存视频的详情信息
            xiaoHongShuService.extractAudioFromVideo(userId,link.get(),videoId);
            stringStringHashMap.put("videoId",videoId);
            stringStringHashMap.put("url",null);
            return R.ok(stringStringHashMap);
        }
        throw new RuntimeException("未提取到链接");
    }
    /**
     * （小红书）根据小红书videoId查询是否已经生成成功的视频地址
     * @param videoId 视频ID
     * @return {"videoId":"视频ID","url":"视频地址",flag:false/true是否完成进度}
     */
    @PostMapping("listDouYinVideoById")
    public R<HashMap<String, Object> > listDouYinVideoById(HttpServletRequest request,String videoId){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("videoId",videoId);
        Object url = xiaoHongShuService.listDouYinVideoById(request,videoId);
        stringStringHashMap.put("url",url);
        stringStringHashMap.put("flag",false);
        if(ObjectUtil.isNotNull(url)){
            stringStringHashMap.put("flag",true);
        }
        return R.ok(stringStringHashMap);
    }

    /**
     * （小红书）查询当前登录用户的所有视频
     * @return
     */
    @PostMapping("listDouYinVideoByUserId")
    public R<List<XiaoHongShuVideoVo>> listDouYinVideoByUserId(HttpServletRequest request){
        return  R.ok(xiaoHongShuService.listDouYinVideoByUserId(request));
    }



    /**
     * （小红书）判断是否需要观看广告(true需要，false不需要)
     * @param video 视频ID
     * @return
     */
    @RequestMapping("queryWatchVideoNum")
    public R<Boolean> queryWatchVideoNum(HttpServletRequest request,@RequestParam("videoId")String video){
        return R.ok(xiaoHongShuService.queryWatchVideoNum(request,video));
    }
    /**
     * （小红书）看完广告后累加广告次数
     * @param videoId 视频ID
     * @return
     */
    @RequestMapping("addWatchVideoNum")
    public void addWatchVideoNum(HttpServletRequest request,@RequestParam("videoId")String videoId){
        xiaoHongShuService.addWatchVideoNum(request,videoId);
    }

}
